﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using WebApiJwtAuth.Models;

namespace WebApiJwtAuth.Controllers
{
    [Produces("application/json")]
    [Route("auth")]
    [ApiController]
    public class AuthController : ControllerBase
    {
        [HttpGet("login")]
        public ApiResponse<string> Login()
        {
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, "2"),
                new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString()),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(ClaimTypes.Role, "admin")
            };

            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("UwItrlfVrqDr01QLpT8AGhF8N9PEJBjH"));
            var signKey = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
            var jwt = new JwtSecurityToken(
                issuer: "http://localhost:5000/",
                audience: "Audience",
                claims: claims,
                expires: DateTime.Now.AddDays(2),
                notBefore: DateTime.Now,
                signingCredentials: signKey
                );

            return new ApiResponse<string>
            {
                Code = 0,
                Message = "登录成功.",
                Data = new JwtSecurityTokenHandler().WriteToken(jwt)
        };
        }
    }
}